#include "udp_echo_server.h"
#include "sys_plat.h"

static int server_port;

static void udp_echo_server_start(void *arg)
{
    // todo 先直接调用系统的socket相关接口
    // WSADATA wsdata;
    // WSAStartup(MAKEWORD(2, 2), &wsdata);

    int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    // struct timeval time;
    // time.tv_sec = 3;
    // time.tv_usec = 0;
    // setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&time, sizeof(time));
    if (s < 0)
    {
        printf("open socket faield!\n");
        return;
    }

    struct sockaddr_in addr;
    plat_memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(server_port);
    if(bind(s, (const struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        printf("bind failed!\n");
        closesocket(s);
        return;
    }

    char buf[BUF_SIZE];
    while(1){
        plat_memset(buf, 0, BUF_SIZE);
        
        struct sockaddr_in from_addr;
        plat_memset(&from_addr, 0, sizeof(from_addr));
        int from_len = sizeof(from_addr);
        plat_memset(buf, 0, BUF_SIZE);
        ssize_t size = size = recvfrom(s, buf, BUF_SIZE, 0, (struct sockaddr *)&from_addr, &from_len);;
        if(size < 0)
        {
            printf("recv message failed!\n");
            break;
        }
        printf("udp echo server recv message:%s\n", buf);

        size = sendto(s, buf, (int)plat_strlen(buf), 0, (const struct sockaddr *)&from_addr, from_len);
        if(size < 0)
        {
            printf("send message failed!\n");
            break;
        }
    }
    closesocket(s);
    return;
}

void udp_echo_server_thread_start(int port)
{
    server_port = port;
    sys_thread_create(udp_echo_server_start, NULL);
}